<?php

namespace app\admin\controller\facrm\thread;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
/**
 * 线索管理
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{

    /**
     * Index模型对象
     * @var \app\admin\model\facrm\thread\Index
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\thread\Index;

    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['type'])
                    ->where($where)
                    ->where(['fa_thread.status'=>1])
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('type')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    
    
    public function zhuanhuan(){

        $info=$this->request->param('ids');
        $this->view->assign('infos', $info);
        $list=Db::name('thread_type')->select();
        $this->assign('lists', $list);

        if ($this->request->isAjax()) {

            $ids=$this->request->param('ids');
            $types=$this->request->param('types_id');
            Db::name('thread')->where('id','in',$ids)->update(['thread_type_id'=>$types]);

            $this->success();
        }


        return $this->view->fetch();

    }

    //获取部门员工

    public function getdownuser(){

        $adminida=$this->request->param('id');  //部门

        $infos=Db::name('admin')->where('pid','eq',$adminida)->select();
        $info=Db::name('admin')->where('id','eq',$adminida)->find();

        $infos[]=$info;



        return json($infos);

    }


    //分配
    public function fenpei(){

        $info=$this->request->param('ids');
        $this->view->assign('infos', $info);




        if ($this->request->isPost()) {

            $ids=$this->request->param('ids');
            $adminida=$this->request->param('adminida');  //部门
            $adminidb=$this->request->param('adminidb');  //单个

            $types=$this->request->param('types');

            $alluser= input('post.allusers/a');


            $listst=Db::name('thread')->where('id','in',$ids)->select();

            //安部门
            if ($types==1){

                if (intval($adminida)<1){
                    $this->error('请选择');
                }




                if (count($alluser)<1){
                    $this->error('请选择');
                }


                    $all=count($alluser);



                    foreach ($listst as $ke=>$key){

                        $vs= ceil($ke % $all);


                        $inserts['name']=$key['name'];
                        $inserts['mobile']=$key['mobile'];
                        $inserts['detail_address']=$key['detail_address'];
                        $inserts['remark']=$key['remark'];
                        $inserts['owner_user_id']=$alluser[$vs];
                        $inserts['create_user_id']=1;
                        $inserts['create_time']=time();
                        $inserts['update_time']=time();
                        $inserts['purchase_total']=$key['money'];
                        $inserts['remark']=$key['remark'];
                        $inserts['purchase_times']=$key['number'];
                        $inserts['tags']=$key['from'];

                        Db::name('facrm_customer')->data($inserts)->insert();
                        Db::name('thread')->where('id','eq',$key['id'])->delete();
                    }
                //平分到

//                if (intval($alluser)<1){{
//
//
//                    $user=Db::name('admin')->where(['id'=>$alluser])->find();
//
//                    if (!$user) {
//                        $this->error('无用户');
//                    }
//
//                    foreach ($listst as $key){
//
//                        $inserts['name']=$key['name'];
//                        $inserts['mobile']=$key['mobile'];
//                        $inserts['detail_address']=$key['detail_address'];
//                        $inserts['remark']=$key['remark'];
//                        $inserts['owner_user_id']=$alluser;
//                        $inserts['create_user_id']=1;
//                        $inserts['create_time']=time();
//                        $inserts['update_time']=time();
//                        $inserts['purchase_total']=$key['money'];
//                        $inserts['remark']=$key['remark'];
//                        $inserts['purchase_times']=$key['number'];
//                        $inserts['tags']=$key['from'];
//
//                        Db::name('facrm_customer')->data($inserts)->insert();
//                        Db::name('thread')->where('id','eq',$key['id'])->delete();
//
//                    }
//
//
//
//
//                }
//
//
//
//
//
            }


            //分给个人
            if ($types==2){

                $user=Db::name('admin')->where(['id'=>$adminidb])->find();
                if (!$user) {
                    $this->error('无用户');
                }

                foreach ($listst as $key){
                    $inserts['name']=$key['name'];
                    $inserts['mobile']=$key['mobile'];
                    $inserts['detail_address']=$key['detail_address'];
                    $inserts['remark']=$key['remark'];
                    $inserts['owner_user_id']=$adminidb;
                    $inserts['create_user_id']=1;
                    $inserts['create_time']=time();
                    $inserts['update_time']=time();
                    $inserts['purchase_total']=$key['money'];
                    $inserts['remark']=$key['remark'];
                    $inserts['purchase_times']=$key['number'];
                    $inserts['tags']=$key['from'];

                    Db::name('facrm_customer')->data($inserts)->insert();
                    Db::name('thread')->where('id','eq',$key['id'])->delete();
                }

            }


            $this->success();
        }


        $alluser=Db::name('admin')->where('id','neq',1)->select();
        $this->assign('alluser',$alluser);


        $all=Db::name('admin')
            ->alias('a')
            ->join('fa_auth_group_access b','a.id=b.uid')
            ->where('a.id','neq',1)
            ->where('b.group_id','eq',3)
            ->select();
        $this->assign('all',$all);


        return $this->view->fetch();



    }


    public function daoru(){

        if ($this->request->isAjax()) {

            $file=$this->request->param('file');
            $types_id=$this->request->param('types_id');

//            $file='/uploads/20240322/9161ca2a27505e73f5b7447f9dd3c696.xlsx';

            $filePath = ROOT_PATH . DS . 'public' . DS . $file;

            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, 'w');
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding !== 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }


            //加载文件
            $insert = [];

                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields = [];

                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = [];

//                    var_dump($values);
                    $row['name']=$values[0];
                    $row['mobile']=$values[1];
                    $row['detail_address']=$values[2];

                    if  ($values[3]){
                        $time=$values[3];
                    }else{
                        $time=date('Y-m-d H:i:s');

                    }

                    $row['create_time']= $values[3];
                    $row['remark']=$values[4];
                    $row['number']=$values[5];
                    $row['money']=$values[6];
                    $row['from']=$values[7];
                    $row['thread_type_id']=$types_id;


                    $ins=Db::name('thread')->where(['mobile'=>$values['1']])->find();

                    if ($ins){
                        Db::name('threads')->data($row)->insert();
                    }

                    Db::name('thread')->data($row)->insert();


                }

            $this->success();
        }

        $list=Db::name('thread_type')->select();
        $this->assign('lists', $list);
        return $this->view->fetch();

    }
    
    
}
